<template>
  <el-dialog
    :visible.sync="localVisible"
    title="订单评论管理"
    width="65%"
    :close-on-click-modal="false"
    center
  >
    <!-- 已有评论区域 -->
    <div class="comment-section">
      <h4>历史评论</h4>
      <el-scrollbar style="max-height: 300px; overflow-y: auto;">
        <div v-if="order && order.commentList && order.commentList.length" class="comments">
          <div
            v-for="comment in order.commentList"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-meta">管理员：{{ comment.adminName }} - {{ comment.createdAt }}</div>
            <div class="comment-actions">
              <el-button size="mini" @click="handleEdit(comment)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(comment.id)">删除</el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无评论" :image-size="100"></el-empty>
      </el-scrollbar>
    </div>

    <!-- 新增/编辑表单 -->
    <div class="form-section">
      <h4>{{ form.id ? '编辑评论' : '添加新评论' }}</h4>
      <el-form ref="form" :model="form" label-width="90px" label-position="left">
        <el-form-item label="评论内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容..."
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-button type="primary" @click="submit" icon="el-icon-edit" round>提交评论</el-button>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import axios from 'axios';

export default {
  name: 'CommentDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    order: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        id: null,
        orderId: null,
        content: ''
      },
      orderId: null
    };
  },
  computed: {
    localVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        // 弹窗打开时初始化数据
        this.orderId = this.order?.id || null;
        this.form = {
          id: null,
          orderId: this.orderId,
          content: ''
        };
      }
    },
    order(newVal) {
      if (newVal && newVal.id) {
        this.orderId = newVal.id;
      }
    }
  },
  methods: {
    async submit() {
      try {
        let res;
        if (this.form.id) {
          res = await this.updateComment();
        } else {
          res = await this.createComment();
        }

        if (res.data.code !== 1) {
          throw new Error(res.data.msg || '操作失败');
        }

        this.$message.success('操作成功');

        // 通知父组件刷新数据
        this.$emit('saved');
        this.localVisible = false;
      } catch (error) {
        console.error("Error submitting comment:", error);
        this.$message.error(`操作失败：${error.message}`);
      }
    },
    async createComment() {
      return await axios.put('/api/admin/order/saveOrUpdateComment', {
        orderId: this.orderId,
        content: this.form.content
      });
    },
    async updateComment() {
      return await axios.put(`/api/admin/order/saveOrUpdateComment`, this.form);
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/admin/order/deleteComment/${id}`);
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || '删除失败');
        }

        this.$message.success('删除成功');

        // 不关闭对话框
        this.$emit('deleted');
        this.localVisible = false;
      } catch (error) {
        console.error("操作失败", error);
        this.$message.error(`删除失败：${error.message}`);
      }
    },
    handleEdit(comment) {
      this.form = {
        id: comment.id,
        orderId: this.orderId,
        content: comment.content
      };
    }
  }
};
</script>

<style scoped>
.comment-section {
  margin-bottom: 20px;
}

.comment-section h4 {
  margin-bottom: 10px;
  font-weight: bold;
  color: #333;
}

.comments {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.comment-item {
  padding: 10px;
  background-color: #f9f9f9;
  border-left: 4px solid #409EFF;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.comment-content {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.comment-meta {
  font-size: 12px;
  color: #888;
  margin-bottom: 5px;
}

.comment-actions {
  text-align: right;
}

.form-section {
  margin-top: 20px;
}

.form-section h4 {
  margin-bottom: 10px;
  font-weight: bold;
  color: #333;
}

.el-button {
  margin-top: 10px;
  transition: all 0.3s ease-in-out;
}

.el-button:hover {
  transform: scale(1.05);
}
</style>